package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/category")
@RestController
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R add(@RequestBody Category c){
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Category::getName,c.getName());
        Category one = categoryService.getOne(lqw);
        if (one != null){
            return R.error("已存在数据!");
        }
        categoryService.save(c);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R page(Integer page ,Integer pageSize){
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        IPage<Category> pageInfo = new Page<>(page,pageSize);
        IPage<Category> iPage = categoryService.page(pageInfo, lqw);
        return R.success(iPage);

    }

    @DeleteMapping
    public R deleteById(long id){
        categoryService.remove(id);
        return R.success("删除成功");
    }

    @PutMapping
    public R updateById(@RequestBody Category c){
        categoryService.updateById(c);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R list(Category c){
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(c.getType()!=null,Category::getType,c.getType());
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }


}
